﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using Shiloh.Job.Api.Models;
using Shiloh.Job.Common.Helper;
using Shiloh.Job.Model.Entities;
using Shiloh.Job.Model.Enums;
using Shiloh.Job.Services.Interfaces;
using Shiloh.Job.Services.Models;
using SqlSugar;
using LoginRequest = Shiloh.Job.Api.Models.LoginRequest;

namespace Shiloh.Job.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserIndividualController : ControllerBase
    {
        private readonly IUserIndividualLoginService _userLoginService;
        public UserIndividualController(IUserIndividualLoginService userLoginService) {
            _userLoginService = userLoginService;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginRequest"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<CommonResponse<IndividualLoginResponse>> Login(LoginRequest loginRequest)
        {
            var factory = new ValidatorFactory();
            var validator = factory.GetValidator(loginRequest.Type);

            if (!validator.Validate(loginRequest, out var errors))
            {
                return CommonResponse<IndividualLoginResponse>.Error(string.Join('|', errors));
            }

            // 根据登录类型处理业务逻辑（如验证密码、验证码等）
            CommonResponse<UserIndividual> serviceResponse;
            switch (loginRequest.Type)
            {
                case LoginWayEnum.Pwd:
                    serviceResponse = await _userLoginService.LoginByPwd(loginRequest.Username, loginRequest.Password);
                    break;
                case LoginWayEnum.Sms:
                    serviceResponse = await _userLoginService.LoginBySms(loginRequest.Phone,loginRequest.Code);
                    break;
                case LoginWayEnum.Wechat:
                    serviceResponse = await _userLoginService.LoginByWechat(loginRequest.WeChatCode);
                    break;
                default:
                    return CommonResponse<IndividualLoginResponse>.Error("不支持的登录方式");
            }
            if (serviceResponse != null && serviceResponse.Success && serviceResponse.Data != null) {
                var user = serviceResponse.Data;
                //gen token
                var token = JwtHelper.IssueJwt(new JwtTokenModel() { Uid = user.Id.ToString(),Role = UserTypeEnum.Individual.ToString()});
                IndividualLoginResponse loginResponse = new IndividualLoginResponse() { Token = token,Username=user.Username};
                return CommonResponse<IndividualLoginResponse>.OK(loginResponse, "登录成功");
            }
            else
            {
                return CommonResponse<IndividualLoginResponse>.Error(serviceResponse?.Message);
            }
        }

        /// <summary>
        /// 一键注册登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<CommonResponse<IndividualLoginResponse>> ResiterAndLogin(IndividualRegsiterLoginRequest request) {
            CommonResponse<UserIndividual> result = await _userLoginService.ResiterAndLogin(request.Phone, request.ValidCode);
            if (result.Success)
            {
                var user = result.Data;
                var token = JwtHelper.IssueJwt(new JwtTokenModel() { Uid = user.Id.ToString(), Role = UserTypeEnum.Individual.ToString() });
                IndividualLoginResponse loginResponse = new IndividualLoginResponse() { Token = token, Username = user.Username };
                return CommonResponse<IndividualLoginResponse>.OK(loginResponse, "登录成功");
            }
            else {
                return CommonResponse<IndividualLoginResponse>.Error(result.Message);
            }
        }
    }
}
